using System.Collections.Generic;
using System.Text;
using UnityEngine;

namespace Scanline.Core
{
    internal class OrderedEdgeContainer
    {
        private readonly Dictionary<int, List<OrderedEdge>> edges = new();
        internal int yMin, yMax;

        internal OrderedEdgeContainer(List<Vector2Int> vertices)
        {
            yMin = int.MaxValue;
            yMax = int.MinValue;
            for (int i = 0; i < vertices.Count; i++)
            {
                yMin = Mathf.Min(yMin, vertices[i].y);
                yMax = Mathf.Max(yMax, vertices[i].y);
                OrderedEdge edge = new(vertices[i], vertices[(i + 1) % vertices.Count], i);
                Add(edge);
            }
        }

        internal void Add(OrderedEdge edge)
        {
            if (edge.yMin == edge.yMax)
                return;
            if (!edges.ContainsKey(edge.yMin))
                edges.Add(edge.yMin, new List<OrderedEdge>());
            edges[edge.yMin].Add(edge);
        }

        internal void SendCurrentEdges(ActiveEdgeContainer activeEdgeContainer)
        {
            int y = activeEdgeContainer.currentY;
            if(edges.ContainsKey(y))
            {
                for (int i = 0; i < edges[y].Count; i++)
                {
                    activeEdgeContainer.Add(edges[y][i]);
                }
                edges.Remove(y);
            }
        }

        public override string ToString()
        {
            StringBuilder sb = new();
            foreach (List<OrderedEdge> list in edges.Values)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    sb.AppendLine(list[i].ToString());
                }
            }
            return sb.ToString();
        }
    }
}